package 并发编程15.线程池;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory;

/**
 * 线程工厂测试类
 *
 * @author idea
 * @data 2019/2/6
 */
public class ThreadFactoryTest implements ThreadFactory {

    private int counter;
    private String name;
    private List<String> stats;

    public ThreadFactoryTest(String name) {
        counter = 0;
        this.name = name;
        stats = new ArrayList<String>();
    }


    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r, name + "-Thread-" + counter);
        counter++;
        stats.add(String.format("Created thread %d with name %s on%s\n", t.getId(), t.getName(), new Date()));
        return t;
    }


    public String getStats() {
        StringBuffer stb = new StringBuffer();
        Iterator<String> it = stats.iterator();
        while (it.hasNext()) {
            stb.append(it.next());
        }
        return stb.toString();
    }

    public static void main(String[] args) {
        ThreadFactoryTest threadFactoryTest = new ThreadFactoryTest("idea");
        Task task = new Task();
        Thread thread = null;
        for (int i = 0; i < 10; i++) {
            thread = threadFactoryTest.newThread(task);
            thread.start();
        }
        System.out.printf("%s\n", threadFactoryTest.getStats());

    }


}

class Task implements Runnable {

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

